package core;

import java.io.*;
import javax.swing.table.AbstractTableModel;

/**
 * Represents an index of data records. Allows easy display of indexed data
 * in a JTable, and provides the ability to write the index to a file.
 * @author john
 *
 */
public abstract class Index extends AbstractTableModel {
	
	protected File indexFile; //, dataDir;
	private int nextId, displayCols;
	
	/**
	 * Creates a new index that saves data to the given file.
	 * @param file		file to save as
	 */
	public Index(File file) {
		indexFile = file;
		nextId = 0;
		displayCols = 0;
	}
	
	/**
	 * Sets the number of columns to display in the table model.
	 * @param n		number of columns
	 */
	public void setDisplayCols(int n) {
		displayCols = n;
	}
	
	/**
	 * Called by subclasses to get the next unique ID number.
	 * @return	ID number
	 */
	protected int nextId() {
		return nextId++;
	}
	
	/**
	 * Saves data to the File given at initialization.
	 */
	public void save() {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(indexFile));
			this.writeObject(oos);
			oos.close();
		} catch(IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * Called by subclasses to load data from an index file.
	 * @param file		file to load from
	 * @param index		an instance of the subclass
	 */
	protected static void load(Index index, File file) {
		try {
			ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
			index.readObject(ois);
			ois.close();
		} catch(IOException ex) {
			ex.printStackTrace();
		} catch(ClassNotFoundException ex) {
			ex.printStackTrace();
		}
	}
	
	
	// TableModel methods
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}
	public int getColumnCount() { 
		return displayCols;
	}
	
	// Serialization methods
	protected void writeObject(ObjectOutputStream out) throws IOException {
		out.writeInt(nextId);
	}
	protected void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		nextId = in.readInt();
	}
}
